package com.smart.mattress.account.server.impl;

import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.smart.mattress.account.server.FileStoreService;

@Service
public class FileStoreServiceImpl implements FileStoreService{

    private Logger logger =  LoggerFactory.getLogger(this.getClass());
    @Autowired
    GridFsTemplate gridFsTemplate;


    @Override
    public boolean saveFile(String filename,String orgname, InputStream file) {
        try {
            DBObject metaData = new BasicDBObject();
            metaData.put("orgname", orgname);
            gridFsTemplate.store(file,filename,metaData);
            return true;
        }catch (Exception e){
            logger.error("save file error:{}",e);
            return false;
        }

    }

    @Override
    public GridFSDBFile findByFileName(String filename) {

        Query query = new Query();
        query.addCriteria(Criteria.where("filename").is(filename));
        GridFSDBFile gridFSDBFile = gridFsTemplate.findOne(query);

        return gridFSDBFile;

    }

    @Override
    public boolean deleteByFileName(String filename) {
        Query query = new Query();
        query.addCriteria(Criteria.where("filename").is(filename));
         try {
             gridFsTemplate.delete(query);
         }catch (Exception e){
             logger.error("删除文件错误",e);
             return false;
         }
        return true;
    }
}
